<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="账号归属人" prop="ownerId">
          <el-select
            v-model="queryParams.ownerId"
            style="width: 150px"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in ownerOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="平台" prop="platform">
          <el-input
            v-model="queryParams.platform"
            placeholder=""
            clearable
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="queryParams.remark"
            placeholder=""
            clearable
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          v-hasPerm="['modules.accounts:platformAccount:add']"
          type="success"
          @click="handleOpenDialog()"
        >
          <template #icon>
            <Plus />
          </template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['modules.accounts:platformAccount:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon>
            <Delete />
          </template>
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          key="ownerId"
          label="账号归属人"
          prop="ownerId"
          min-width="150"
          align="center"
        >
          <template #default="{ row }: { row: any }">
            {{ ownerOptions.find((item: any) => item.id === row.ownerId).name }}
          </template>
        </el-table-column>
        <el-table-column
          key="platform"
          label="平台"
          prop="platform"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="username"
          label="用户名"
          prop="username"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="password"
          label="密码"
          prop="password"
          min-width="150"
          align="center"
        />
        <el-table-column key="remark" label="备注" prop="remark" min-width="150" align="center" />
        <el-table-column
          key="picUrls"
          label="多张图片"
          prop="picUrls"
          min-width="150"
          align="center"
        >
          <template #default="{ row }">
            <div v-if="row.picUrls.length > 0" style="display: flex; gap: 8px">
              <el-image
                v-for="(url, index) in row.picUrls.split(',')"
                :key="index"
                :src="url"
                :preview-src-list="row.picUrls.split(',')"
                style="width: 60px; height: 60px; object-fit: cover"
                fit="cover"
                preview-teleported
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['modules.accounts:platformAccount:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon>
                <Edit />
              </template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['modules.accounts:platformAccount:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon>
                <Delete />
              </template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 账户明细表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      destroy-on-close
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="账户归属人" prop="ownerId">
          <el-select v-model="formData.ownerId" style="width: 100%" placeholder="请选择" clearable>
            <el-option
              v-for="item in ownerOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="平台" prop="platform">
          <el-input v-model="formData.platform" placeholder="" />
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" placeholder="" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="" />
        </el-form-item>

        <el-form-item label="多张图片" prop="picUrls">
          <MultiImageUpload v-model="picUrls" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import MultiImageUpload from "@/components/Upload/MultiImageUpload.vue";

defineOptions({
  name: "PlatformAccount",
  inheritAttrs: false,
});

import PlatformAccountAPI, {
  PlatformAccountPageVO,
  PlatformAccountForm,
  PlatformAccountPageQuery,
} from "@/api/modules/accounts/platform-account";
import AccountOwnerAPI from "@/api/modules/accounts/account-owner";

const queryFormRef = ref();
const dataFormRef = ref();
const picUrls = ref([]);

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<PlatformAccountPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 账户明细表格数据
const pageData = ref<PlatformAccountPageVO[]>([]);
const ownerOptions = ref<any>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 账户明细表单数据
const formData = reactive<PlatformAccountForm>({});

watch(
  () => picUrls.value,
  () => {
    formData.picUrls = picUrls.value.join(",");
  },
  {
    deep: true,
  }
);

// 账户明细表单校验规则
const rules = reactive({
  id: [{ required: true, message: "请输入", trigger: "blur" }],
  ownerId: [{ required: true, message: "请输入", trigger: "blur" }],
});

/** 查询账户归属人 */
function myHandleQuery() {
  loading.value = true;
  AccountOwnerAPI.getPage({ pageNum: 1, pageSize: 100 })
    .then((data) => {
      ownerOptions.value = data.list;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 查询账户明细 */
function handleQuery() {
  loading.value = true;
  PlatformAccountAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置账户明细查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开账户明细弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = false; // 防止旧内容显示
  if (id) {
    dialog.title = "修改账户明细";
    PlatformAccountAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
      picUrls.value = (data.picUrls?.split(",") || []) as any;
      nextTick(() => {
        dialog.visible = true; // 数据就绪后再打开弹窗
      });
    });
  } else {
    dialog.title = "新增账户明细";
    picUrls.value = [];
    dialog.visible = true;
  }
}

/** 提交账户明细表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        PlatformAccountAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        PlatformAccountAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭账户明细弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除账户明细 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      PlatformAccountAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
  myHandleQuery();
});
</script>
